package com.epoint.mobileoa.ui.attachmanager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.Arithmetic;
import com.epoint.mobileoa.tools.IOHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.ui.init.InitView;

/**
 * @author liyc
 * @time 2012-2-9 上午10:00:44
 * @annotation 附件管理
 */
public class AttachManagerView extends SuperView{

	private ListView lv;
	private String ATTACH_PATH;
	private List<Map<String, Object>> mData;

	@Override
	public void initControls(){

		//查询按钮
		if("1".equals(PropertiesHelp.getProperty(this,"FileAttachSearch"))){
//			top_right_bt.setBackgroundResource(R.drawable.top_right_search);
			top_right_bt.setText("查找");
			top_right_bt.setVisibility(View.VISIBLE);
			top_right_bt.setOnClickListener(this);
		}

		ATTACH_PATH = "/"+InitView.MobileOaMainStoreFolder+"/"+getString(R.string.sdforder)+"/attachdownload";
		lv = (ListView) findViewById(R.id.lv_mailstyle);
		IOHelp.FoldCreate(ATTACH_PATH);
		lv.setOnItemLongClickListener(this);
		lv.setOnItemClickListener(this);
		refreshData();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		String filepath = mData.get(position).get("path").toString();
		IOHelp.doOpenFile(AttachManagerView.this, filepath);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position1, long id) {

		final int fileposition = position1;
		AlertHelp.showAlertMenu(this, "文件操作", new String[]{"重命名","删除","文件属性"}, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which==0){
					LayoutInflater inflater2 = LayoutInflater.from(AttachManagerView.this);
					LinearLayout ll = (LinearLayout) inflater2.inflate(R.layout.alertinput_editview, null);
					final EditText et = (EditText) ll.findViewById(R.id.ai_et);
					et.setText(mData.get(fileposition).get("title").toString());
					new AlertDialog.Builder(AttachManagerView.this)
					.setIcon(R.drawable.epoint2)
					.setTitle("重命名")
					.setView(ll)
					.setPositiveButton("保存", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							String path = mData.get(fileposition).get("path").toString();
							String prefiledir = path.substring(0,path.lastIndexOf("/"));
							File f = new File(mData.get(fileposition).get("path").toString());
							f.renameTo(new File(prefiledir+"/"+et.getText().toString()));
							refreshData();
						}
					})
					.setNegativeButton("取消", null)
					.create().show();
				}
				else if(which==1){
					class DialogListener implements
					android.content.DialogInterface.OnClickListener {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							File file = new File(mData.get(fileposition).get("path").toString());
							if (file.exists()) {
								file.delete();
							}
							refreshData();
						}
					}

					TextView tv = new TextView(AttachManagerView.this);
					tv.setTextColor(Color.YELLOW);
					tv.setTextSize(18);
					Spanned source = Html
							.fromHtml("<font color=white>确认删除文件<br/></font><font color=red>"
									+ mData.get(fileposition).get("title").toString()
									+ "</font><br/><font color=white>？</font>");
					tv.setText(source);
					AlertDialog ad = new AlertDialog.Builder(AttachManagerView.this)
					.setIcon(R.drawable.epoint2)
					.setTitle("提示").setView(tv).setPositiveButton("是",
							new DialogListener()).setNegativeButton(
									"否", null).create();
					ad.show();
				}
				else if(which==2){
					File f = new File(mData.get(fileposition).get("path").toString());
					AlertHelp.showFileAttributeAlert2(AttachManagerView.this, f);
				}
			}
		});
		return super.onItemLongClick(parent, view, position1, id);
	}

	@Override
	public void onClick(View v) {
		if(v==top_right_bt){
			LayoutInflater inflater = LayoutInflater.from(AttachManagerView.this);
			LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.alertinput_editview, null);
			final EditText et = (EditText) ll.findViewById(R.id.ai_et);
			et.setHint("输入文件名");
			new AlertDialog.Builder(AttachManagerView.this)
			.setIcon(R.drawable.epoint2)
			.setTitle("附件查找")
			.setView(ll)
			.setPositiveButton("查找", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					if(et.getText().toString().length()>0){
						mData = getData(ATTACH_PATH);
						List<Map<String, Object>> mData_search = new ArrayList<Map<String,Object>>();
						for(int i=0;i<mData.size();i++){
							if(mData.get(i).get("title").toString().contains(et.getText().toString())){
								mData_search.add(mData.get(i));
							}
						}
						mData = mData_search;
						MyAdapter adapter = new MyAdapter(AttachManagerView.this);
						lv.setAdapter(adapter);
					}
					else{
						refreshData();
					}
				}
			})
			.setNegativeButton("取消", null)
			.create().show();
		}
	}

	public void refreshData() {
		mData = getData(ATTACH_PATH);

		Long[] time = new Long[mData.size()];
		for(int i=0;i<mData.size();i++){
			time[i] = (Long) mData.get(i).get("time");
		}

		time = Arithmetic.sort(time);

		List<Map<String, Object>> templist = new ArrayList<Map<String,Object>>();
		for(int i=mData.size()-1;i>=0;i--){
			for(int j=0;j<mData.size();j++){
				if(time[i]==(Long) mData.get(j).get("time")){
					templist.add(mData.get(j));
				}
			}
		}

		mData = templist;
		MyAdapter adapter = new MyAdapter(this);
		lv.setAdapter(adapter);
	}

	private List<Map<String, Object>> getData(String dir) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		File file = new File(dir);

		File[] files = file.listFiles();//所有文件夹

		for (File currentFile : files) {
			if(currentFile.isDirectory()){
				File[] subfiles = currentFile.listFiles();
				for(File subfile:subfiles){
					if(!subfile.isDirectory()){
						map = new HashMap<String, Object>();
						map.put("path", subfile.getAbsolutePath());
						map.put("time", subfile.lastModified());
						map.put("title", subfile.getName());
						Long time = subfile.lastModified();
						// 格式化时间字符串
						String timestr = DateFormat.format("yyyy.MM.dd kk:mm:ss", time)
								.toString();
						map.put("info", timestr);
						map.put("icon", R.drawable.img_file_48);
						String hz = subfile.getName();
						if (hz.lastIndexOf(".doc") > -1||hz.lastIndexOf(".docx") > -1) {
							map.put("icon", R.drawable.img_attach_doc);
						} 
						else if (hz.lastIndexOf(".xls") > -1||hz.lastIndexOf(".xlsx") > -1) {
							map.put("icon", R.drawable.img_attach_excel);
						} 
						else if (hz.lastIndexOf(".ppt") > -1) {
							map.put("icon", R.drawable.img_attach_ppt);
						}
						else if(hz.lastIndexOf(".rar") > -1){
							map.put("icon", R.drawable.img_rar_48);
						}
						else if(hz.lastIndexOf(".zip") > -1){
							map.put("icon", R.drawable.img_zip_48);
						}
						else if(hz.lastIndexOf(".jpeg") > -1||hz.lastIndexOf(".jpg")>-1){
							map.put("icon", R.drawable.img_jpg_48);
						}
						else if(hz.lastIndexOf(".png") > -1){
							map.put("icon", R.drawable.img_pngb_48);
						}
						else if(hz.lastIndexOf(".mp3") > -1){
							map.put("icon", R.drawable.img_mp3b_48);
						}
						else if(hz.lastIndexOf(".txt") > -1){
							map.put("icon", R.drawable.img_txt_48);
						}
						else if(hz.lastIndexOf(".pdf") > -1){
							map.put("icon", R.drawable.img_pdf_48);
						}
						else if(hz.lastIndexOf(".html") > -1){
							map.put("icon", R.drawable.img_html_48);
						}

						list.add(map);
					}
				}
			}
		}

		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Menu.FIRST, 1, "清空所有附件").setIcon(R.drawable.menu_delete);
		return super.onCreateOptionsMenu(menu);
	}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			Builder dlg = new AlertDialog.Builder(AttachManagerView.this)
			.setIcon(R.drawable.epoint2)
			.setTitle("确认清空所有附件吗？").setPositiveButton(
					"是",new DialogInterface.OnClickListener() // 设置事件监听
					{
						public void onClick(DialogInterface dialog,
								int whichButton) {
							IOHelp.deleteFile(new File(ATTACH_PATH));
							File f = new File(ATTACH_PATH);
							if(!f.exists()){
								f.mkdirs();
							}
							refreshData();
							Toast.makeText(AttachManagerView.this, "附件已全部清空！", 1000).show();
						}
					})
					.setNegativeButton("否",null);
			dlg.create().show();
			break;
		}	
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void refresh(Object... param) {
	}

	@Override
	public int getLayoutInt() {
		return R.layout.layout_mailstyle;
	}

	@Override
	public String setTitle() {
		return getString(R.string.fjgl);
	}

	public final class ViewHolder {
		public ImageView iv;
		public TextView tv;
	}

	class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.lv_attach,
						null);
				holder.iv = (ImageView) convertView
						.findViewById(R.id.lv_attach_iv);
				holder.tv = (TextView) convertView
						.findViewById(R.id.lv_attach_tv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.iv.setBackgroundResource((Integer) mData.get(position)
					.get("icon"));
			final String fileName = (String) mData.get(position).get("title");
			holder.tv.setText(fileName);
			setTextViewFontColor(holder.tv);
			return convertView;
		}
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}

}
